<?php

namespace app\command;

use app\common\lib\Common;
use app\logic\cron\UserRechargeOrderLogic;
use support\Log;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Webman\Event\Event;
use support\Redis;

/**
 * 充值订单统计
 * Class CronUserRechargeOrder
 * @package app\command
 */
class CronUserRechargeOrder extends Command
{
    protected static $defaultName = 'cron:user:recharge:order';
    protected static $defaultDescription = 'Cron User Recharge Order statistics';

    /**
     * @return void
     */
    protected function configure()
    {
        //发布执行结束
        Event::dispatch('console.start', []);

        $this->addArgument('type', InputArgument::OPTIONAL, '执行类型 如果传1，则不限制执行此时，调用就执行');
        Common::initTaskConfig();
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $type = $input->getArgument('type');

        if ($type != 1) {
            $key = "cron:UserRechargeOrder:statistics:" . date('Ymd');
            if (!Redis::setNx($key, 1)) {
                Log::info("cron:user:recharge:order 重复执行任务");
                return self::FAILURE;
            }
            Redis::expire($key, 3600);
        }

        try {
            $startTime = round(microtime(true), 4);
            Log::info("订单统计任务：-1" );
            $result = UserRechargeOrderLogic::getInstance()->statistics();
            Log::info("订单统计任务：-2" );
            $ttls = round(round(microtime(true), 4) - $startTime, 4);
            //发布执行结束
            Event::dispatch('console.terminate', ['php webman ' . self::$defaultName, $result, $ttls]);

            return self::SUCCESS;
        } catch (\Throwable $e) {
            Common::consoleExecptionReport('php webman ' . self::$defaultName, $e);
            Log::info("订单统计执行异常：" . $e->getMessage());
            return self::FAILURE;
        }
    }
}
